﻿using HealthcareSystem.API.Read.Application.Command;
using HealthcareSystem.Domain;
using MediatR;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel
{
    /// <summary>
    /// 登录处理方法
    /// </summary>
    public class LoginCommandHandel : IRequestHandler<LoginCommand, ApiResult<Login>>
    {
        /// <summary>
        /// 登录仓储
        /// </summary>
        IBaseRepository<Login> loginRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="loginRep"></param>
        public LoginCommandHandel(IBaseRepository<Login> loginRep)
        {
            this.loginRep = loginRep;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<Login>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var user = loginRep.GetAll().FirstOrDefault(o => o.UserName == request.UserName);
            if (user == null)
            {
                return new ApiResult<Login>()
                {
                    Code = ResultCode.Same,
                    Data = null,
                    Message = "用户名不存在"
                };
            }
            if (user.UserPass == request.UserPass)
            {
                return new ApiResult<Login>()
                {
                    Code = ResultCode.Success,
                    Data = user,
                    Message = "登录成功"
                };
            }
            return new ApiResult<Login>()
            {
                Code = ResultCode.Error,
                Data = null,
                Message = "登录失败"
            };
        }
    }
}
